package com.supermarket.exception;

import com.supermarket.common.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseResult handleException(Exception ex) {
        // 使用日志框架记录异常信息
        logger.error("发生异常: ", ex.getMessage(), ex);
        return ResponseResult.error(400, "服务器内部错误");
    }

   /**
    * 用户异常
    */
   @ExceptionHandler(UserException.class)
   @ResponseStatus(HttpStatus.BAD_REQUEST)
   public ResponseResult<String> handleBusinessException(UserException ex) {
       return ResponseResult.error(400, ex.getMessage());
   }

    /**
     * 处理特定的业务异常（假设有一个自定义的业务异常类）
    */
    @ExceptionHandler(NoResourceFoundException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseResult<String> handleBusinessException(NoResourceFoundException ex) {
        logger.error("访问未知文件: ", ex.getMessage());
        return ResponseResult.error(400, ex.getMessage());
    }

//    /**
//     * 处理特定的业务异常（假设有一个自定义的业务异常类）
//     */
//    @ExceptionHandler(BusinessException.class)
//    @ResponseStatus(HttpStatus.BAD_REQUEST)
//    public ResponseResult<String> handleBusinessException(BusinessException ex) {
//        return ResponseResult.error(400, ex.getMessage());
//    }
}